import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:puppy_store/models/goods_detail_model.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_appBar.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_bottom_bar.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_details.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_info.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_options.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_recommends.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_similar.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_title_appBar.dart';
// import 'package:puppy_store/pages/goods_detail/goods_detail_title_appBar.dart';
import 'package:puppy_store/pages/home/widgets/loadingAnimation.dart';
import 'package:puppy_store/service/goods_detail_api.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_evaluation.dart';

class GoodsDetailPage extends StatefulWidget {
  const GoodsDetailPage({required this.id, super.key});
  // 商品的ID
  final String id;

  @override
  State<GoodsDetailPage> createState() => _GoodsDetailPageState();
}

class _GoodsDetailPageState extends State<GoodsDetailPage> {
  GoodsDetailModel? _goodsDetailModel;

  final List<GlobalKey> _keys = [
    GlobalKey(debugLabel: 'goods'),
    GlobalKey(debugLabel: 'comments'),
    GlobalKey(debugLabel: 'details'),
    GlobalKey(debugLabel: 'recommends'),
  ];

  double _screenHeight = 0.00;
  double _appBarHeight = 0.00;

  // 滚动组件控制器
  late ScrollController _scrollController;

  // 加载商品详情数据
  void _loadGoodsDetailData() async {
    // String id = '4000914'; // 测试上平Id
    // String id = '1369155859933827074'; // 测试上平Id
    try {
      _goodsDetailModel = await GoodsDetailApi.getGoodsDetail(
        widget.id, // 测试完成之后, 替换下面的id
        // id,
      );
      setState(() {});
      debugPrint("商品详情数据: $_goodsDetailModel");
    } on DioException catch (e) {
      EasyLoading.showToast(e.response!.data['message']);
    }
  }

  // 标题点击监听事件
  void _titleOnTap(int index) {
    // 商品详情内容定位的位置: 商品详情页已滚动的距离 + 内容组件的纵坐标 - 顶部导航栏高度
    double locationY = _getLocationY(index);
    double point = _scrollController.offset + locationY - _appBarHeight;
    _scrollController.animateTo(
      point,
      duration: Duration(milliseconds: 300),
      curve: Curves.ease,
    );
  }

  // 获取组件的在屏幕中的纵坐标
  double _getLocationY(int index) {
    // // 评价信息纵坐标 获取方法
    // RenderBox box = _keys[1].currentContext?.findRenderObject() as RenderBox;
    // // Offset.zero 表示相对于屏幕的左上角坐标
    // Offset location = box.localToGlobal(Offset.zero);
    // // 读取纵坐标
    // double locationY = location.dy;
    // debugPrint("商品详情页滚动中的距离: ${locationY}");

    RenderBox box =
        _keys[index].currentContext?.findRenderObject() as RenderBox;
    // Offset.zero 表示相对于屏幕的左上角坐标
    Offset location = box.localToGlobal(Offset.zero);
    return location.dy;
  }

  // 监听商品详情页滚动中的事件
  void _goodsDetailOnCroll(double offset) {
    // 获取商品, 评价, 详情,推荐的纵坐标
    double goodsY = _getLocationY(0);
    double commentsY = _getLocationY(1);
    double detailsY = _getLocationY(2);
    double recommendsY = _getLocationY(3);

    debugPrint("商品详情页滚动中的距离: $goodsY - $recommendsY - $detailsY - $commentsY");

    // 滚动高度/轮播图高度 - 顶部导航栏高度
    double opacity = offset / (_screenHeight * 0.382 - _appBarHeight);
    if (opacity > 1) {
      opacity = 1;
    }
    if (opacity < 0) {
      opacity = 0;
    }
    // 44444 在这里向appBar传递透明度
    goodsDetailAppBarKey.currentState?.getGoodsDetailAppBarOpacity(opacity);
    // 55555 向顶部TitleAppBar传递透明度
    goodsDetailTitleAppBarKey.currentState?.getGoodsDetailTitleAppBarOpacity(
      opacity,
      goodsY,
      commentsY,
      detailsY,
      recommendsY,
    );

    debugPrint("商品详情页滚动中的事件: $opacity");
  }

  @override
  void initState() {
    _loadGoodsDetailData();
    _scrollController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕高度
    _screenHeight = MediaQuery.of(context).size.height;

    // 顶部导航栏高度 kToolbarHeight 是系统提供的常量, 表示顶部导航栏的高度
    _appBarHeight = kToolbarHeight + MediaQuery.of(context).padding.top;

    return Scaffold(
      body:
          _goodsDetailModel != null
              ? Stack(
                children: [
                  // 页面内容
                  Column(
                    children: [
                      // 商品详情内容
                      // 注意: 在Row和Column中,布局滚动组件时,如果滚动组件没有明确的约数大小时,会报错
                      // 解决办法:
                      // 1. 给滚动组件设置一个明确的高度, 需要计算比较麻烦
                      // 2. 使用Expanded组件, 给滚动组件设置一个权重, 这样滚动组件就会自动适应父组件的高度
                      Expanded(
                        child: NotificationListener(
                          onNotification: (
                            ScrollNotification scrollNotification,
                          ) {
                            // 监听滚动组件滚动中
                            if (scrollNotification
                                    is ScrollUpdateNotification &&
                                scrollNotification.depth ==
                                    0 // 监听滚动的层级 0 表示最底层滚动组件
                                    ) {
                              _goodsDetailOnCroll(
                                scrollNotification.metrics.pixels,
                              );
                            }

                            // 监听滚动结束
                            if (scrollNotification is ScrollEndNotification &&
                                scrollNotification.depth == 0) {
                              // 内容滚动结束之后,取消点击标记 设置_isClick = false
                              goodsDetailTitleAppBarKey.currentState
                                  ?.cancelTab();
                            }

                            return true; // true: 阻止冒泡, false: 不阻止冒泡  监听的下面ScrollView的滚动事件
                          },
                          child: CustomScrollView(
                            // 滑动控制器
                            controller: _scrollController,
                            // 滑动方向
                            scrollDirection: Axis.vertical,
                            // 是否允许滑动
                            // physics: NeverScrollableScrollPhysics(),

                            // 是否允许滑动
                            slivers: [
                              // 商品基本信息
                              SliverToBoxAdapter(
                                child: Container(
                                  key: _keys[0],
                                  child: GoodsDetailInfoWidget(
                                    mainPictures:
                                        _goodsDetailModel!.mainPictures,
                                    price: _goodsDetailModel!.price,
                                    name: _goodsDetailModel!.name,
                                    desc: _goodsDetailModel!.desc,
                                    brand: _goodsDetailModel!.brand,
                                  ),
                                ),
                              ),
                              // 商品规格选项
                              SliverToBoxAdapter(
                                child: Container(
                                  child: GoodsDetailOptionsWidget(
                                    goodsDetailModel: _goodsDetailModel,
                                    key: goodsDetailOptionsKey,
                                  ),
                                ),
                              ),
                              // 商品评价信息
                              SliverToBoxAdapter(
                                child: Padding(
                                  key: _keys[1],
                                  padding: EdgeInsets.only(top: 8.0),
                                  child: GoodsDetailEvaluationWidget(
                                    evaluationInfoModel:
                                        _goodsDetailModel!.evaluationInfo,
                                  ),
                                ),
                              ),
                              // 同类推荐和24小时热销
                              SliverToBoxAdapter(
                                child: Padding(
                                  padding: EdgeInsets.only(top: 8.0),
                                  child: GoodsDetailSimilarWidget(
                                    similarProducts:
                                        _goodsDetailModel!.similarProducts,
                                    hotByDay: _goodsDetailModel!.hotByDay,
                                  ),
                                ),
                              ),
                              // 商品图文详情
                              SliverToBoxAdapter(
                                child: Padding(
                                  key: _keys[2],
                                  padding: EdgeInsets.only(top: 8.0),
                                  child: GoodsDetailDetailsWidget(
                                    details: _goodsDetailModel!.details,
                                  ),
                                ),
                              ),
                              // 热门商品推荐
                              SliverToBoxAdapter(
                                child: Padding(
                                  key: _keys[3],
                                  padding: EdgeInsets.only(top: 8.0),
                                  child: GoodsDetailRecommendsWidget(
                                    recommends: _goodsDetailModel!.recommends,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      // 底部操作栏
                      GoodsDetailBottomBar(),
                    ],
                  ),
                  // 顶部导航栏 普通导航栏 +  标题导航栏
                  GoodsDetailTitleAppBar(
                    key: goodsDetailTitleAppBarKey,
                    titleOnTap: _titleOnTap,
                  ), // 标题导航栏
                  GoodsDetailAppBar(key: goodsDetailAppBarKey), // 普通导航栏
                ],
              )
              : LoadingAnimation(),
    );
  }
}
